//
//  HttpClient.m
//  AFNetworking
//
//  Created by liusanchun on 14-1-12.
//  Copyright (c) 2014年 liusanchun. All rights reserved.
//

#import "HttpClient.h"
#import "AFHTTPRequestOperationManager.h"
#import "AFURLSessionManager.h"
typedef NS_ENUM(NSUInteger, HttpError) {
    HttpErrorServerInternalError = 500,
    HttpErrorBadRequest = 400,
    HttpErrorUnauthorized = 401,
    HttpErrorForbidden = 403,
    HttpErrorNotFound = 404,
    HttpErrorRequestTimeout = 408,
};

static HttpClient *httpClient;

@implementation HttpClient

- (id)init
{
    self = [super init];
    if (self) {
        _httpHeaders = [[NSMutableDictionary alloc] init];
    }
    return self;
}

+ (HttpClient*)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        httpClient = [[HttpClient alloc] init];
    });
    return httpClient;
}

/**
 *  添加HTTPHeader
 *
 *  @param value HTTPHeader值
 *  @param field HTTPHeader键
 */
- (void)addValue:(NSString*)value forHTTPHeaderField:(NSString *)field
{
    [_httpHeaders setValue:value
                    forKey:field];
}

/**
 *  发起HTTP请求
 *
 *  @param url        请求URL地址
 *  @param parameters 请求参数
 *  @param timeout    请求超时时间
 *  @param method     请求方式，包括POST、GET
 *  @param success    成功回调
 *  @param failure    失败回调
 */
- (void)sendRequest:(NSString*)url
         Parameters:(NSMutableDictionary*)parameters
            Timeout:(int)timeout
             Method:(NSString*)method
            Success:(void(^)(id result))success
            Failure:(void(^)(NSString* message, NSError* error))failure;
{
    
    if ([AppDelegate shareDelegate].user) {
        NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
           [parameters setObject:uid forKey:@"uid"];
    }
     if ([method isEqualToString:@""]
        || method == NULL) {
        method = @"POST";
    }
    //构建GET请求的字符串
    NSString *getUrl = [NSString stringWithFormat:@"%@?", url];
    for (NSString *key in [parameters allKeys]) {
        getUrl = [getUrl stringByAppendingFormat:@"%@=%@&", key, [parameters objectForKey:key]];
    }
    NSLog(@"GET URL > %@", [getUrl substringToIndex:getUrl.length - 1]);
    if ([[method uppercaseString] isEqualToString:@"GET"]) {
        [self sendGetRequest:url
                     Timeout:timeout
                  Parameters:parameters
                     Success:success
                     Failure:failure];
    }
    if ([[method uppercaseString] isEqualToString:@"POST"]) {
        [self sendPostRequest:url
                      Timeout:timeout
                   Parameters:parameters
                      Success:success
                      Failure:failure];
    }
}
- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@""
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0,
                                                      [outputStr length])];
    
    return
    [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
/**
 *  发起HTTP GET请求
 *
 *  @param url        请求URL地址
 *  @param timeout    请求超时时间
 *  @param parameters 请求参数
 *  @param success    成功回调
 *  @param failure    失败回调
 */
- (void)sendGetRequest:(NSString*)url
               Timeout:(int)timeout
            Parameters:(NSMutableDictionary*)parameters
               Success:(void(^)(id result))success
               Failure:(void(^)(NSString* message, NSError* error))failure;
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = timeout;
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer new];
 //    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager.requestSerializer setValue:@"application/json"
//                     forHTTPHeaderField:@"Content-Type"];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url
      parameters:parameters
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSLog(@"请求结果:%@",responseObject);
             success(responseObject);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"错误结果:%@",error);
             NSString *message = nil;
             switch (operation.response.statusCode) {
                 case HttpErrorNotFound:
                     message = @"未找到接口地址";
                     break;
                 case HttpErrorServerInternalError:
                     message = @"内部服务器错误";
                     break;
                 case HttpErrorRequestTimeout:
                     message = @"请求超时";
                     break;
                 case HttpErrorForbidden:
                     message = @"访问被拒绝";
                     break;
                 case HttpErrorUnauthorized:
                     message = @"访问未授权";
                     break;
                 default:
                     break;
             }
             failure(message, error);
         }];
}

/**
 *  发起HTTP POST请求
 *
 *  @param url        请求URL地址
 *  @param timeout    请求超时时间
 *  @param parameters 请求参数
 *  @param success    成功回调
 *  @param failure    失败回调
 */
- (void)sendPostRequest:(NSString*)url
                Timeout:(int)timeout
             Parameters:(NSMutableDictionary*)parameters
                Success:(void(^)(id result))success
                Failure:(void(^)(NSString* message, NSError* error))failure;
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
     manager.requestSerializer.timeoutInterval = timeout;
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    if ([url isEqualToString:@"http://yimisns.com/index.php/User/api/delete_kuaipai"]) {
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    }
 
    for (NSString *key in self.httpHeaders) {
        [manager.requestSerializer setValue:[self.httpHeaders objectForKey:key]
                         forHTTPHeaderField:key];
    }
    [manager POST:url
       parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSLog(@"请求结果:%@",responseObject);
              success(responseObject);
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"错误结果:%@",error);
              NSString *message = nil;
              NSLog(@"%ld",(long)operation.response.statusCode);
              switch (operation.response.statusCode) {
                  case HttpErrorNotFound:
                      message = @"未找到接口地址";
                      break;
                  case HttpErrorServerInternalError:
                      message = @"内部服务器错误";
                      break;
                  case HttpErrorRequestTimeout:
                      message = @"请求超时";
                      break;
                  case HttpErrorForbidden:
                      message = @"访问被拒绝";
                      break;
                  case HttpErrorUnauthorized:
                      message = @"访问未授权";
                      break;
                  default:
                      break;
              }
              failure(message, error);
          }];
}

/**
 *  根据URL地址下载文件，并保存到指定的文件路径
 *
 *  @param url      URL下载地址
 *  @param savePath 文件保存路径
 *  @param success  成功回调
 *  @param failure  失败回调
 */
- (void)downloadRequest:(NSString*)url
               SavePath:(NSString*)savePath
                Success:(void(^)(id result))success
                Failure:(void(^)(NSString* message, NSError* error))failure
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request
                                                                     progress:nil
                                                                  destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
                                                                      return [NSURL fileURLWithPath:savePath];
                                                                  } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
                                                                      if (error) {
                                                                          
                                                                          failure(@"下载错误", error);
                                                                      } else {
                                                                          success(filePath);
                                                                      }
                                                                  }];
    [downloadTask resume];
}

/**
 *  上传数据
 *
 *  @param url        上传数据接收的URL地址
 *  @param fileData   数据流
 *  @param parameters 其他参数
 *  @param success    成功回调
 *  @param failure    失败回调
 */
- (void)uploadRequest:(NSString*)url
             FileData:(NSData*)fileData
           Parameters:(NSMutableDictionary*)parameters
              Success:(void(^)(id result))success
              Failure:(void(^)(NSString* message, NSError* error))failure
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    if (parameters) {
        NSString *param = @"";
        for (NSString *key in [parameters allKeys]) {
            [param stringByAppendingFormat:@"%@=%@&", key, [parameters objectForKey:key]];
        }
        if (param.length > 0) {
            param = [param substringToIndex:param.length - 1];
            [request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
        }
        
    }
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request
                                                               fromData:fileData
                                                               progress:nil
                                                      completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
                                                          if (error) {
                                                              failure(@"上传错误", error);
                                                          } else {
                                                              success(responseObject);
                                                          }
                                                      }];
    [uploadTask resume];
}

@end
